<template>
    <page-container>
        <div class="ant-pro-table">
            <div class="ant-pro-table-search">
                <a-form layout="horizontal">
                    <a-row :gutter="15" type="flex" justify="start">
                        <a-col :xs="12" :sm="12" :md="6" :lg="3">
                            <a-form-item>
                                <a-select
                                    ref="select"
                                    v-model:value="queryParams.orderType"
                                    placeholder="工单类型"
                                    :options="
                                        Object.keys(typeMap).map(item => ({
                                            label: typeMap[item],
                                            value: item,
                                        }))
                                    "
                                    allow-clear
                                    @change="handleSearch()"
                                ></a-select>
                            </a-form-item>
                        </a-col>
                        <template v-if="expand">
                            <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                <a-form-item>
                                    <a-select
                                        ref="select"
                                        v-model:value="queryParams.orderType"
                                        placeholder="工单类型"
                                        :options="
                                            Object.keys(typeMap).map(item => ({
                                                label: typeMap[item],
                                                value: item,
                                            }))
                                        "
                                        allow-clear
                                        @change="handleSearch()"
                                    ></a-select>
                                </a-form-item>
                            </a-col>
                        </template>

                        <a-col :xs="24" :sm="24" :md="12" :lg="8">
                            <a-button @click="handleSearch" type="primary">搜索</a-button>
                            <a-button @click="handleReset" class="ml-5px">重置</a-button>
                            <a-button class="ml-5px" type="primary" @click="handleAdd" v-permission="[`yfwy:order-classify:create`]">
                                <plus-outlined />
                                新建
                            </a-button>
                            <a-button class="ml-5px" @click="handleExport" :loading="exportLoading" v-permission="[`yfwy:order-classify:export`]">
                                <download-outlined />
                                导出
                            </a-button>
                            <a-button type="text" class="ml-5px" @click="expand = !expand">
                                <template v-if="expand">
                                    <up-outlined />
                                </template>
                                <template v-else>
                                    <down-outlined />
                                </template>
                            </a-button>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <a-card :body-style="{ padding: 0 }" ref="elRef">
                <a-table
                    :row-class-name="stripe"
                    :size="state.tableSize"
                    :loading="state.loading"
                    :columns="dynamicColumns"
                    :data-source="state.dataSource"
                    :pagination="{
                        'show-size-changer': true,
                        current: state.current,
                        pageSize: state.pageSize,
                        total: state.total,
                        showTotal: total => `共 ${total} 条`,
                    }"
                    ref="tableRef"
                    :getPopupContainer="_trigger => tableRef.$el"
                    :scroll="{ x: 1150, y: appStore.tableHeight }"
                    @change="handleTableChange"
                >
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.dataIndex === 'status'">
                            <a-badge :status="statusMap[record.status].status" :text="statusMap[record.status].text" />
                        </template>
                        <template v-if="column.dataIndex === 'action'">
                            <a-space>
                                <a @click="handleEdit(record)" v-permission="[`yfwy:order-classify:update`]">编辑</a>
                                <a-popconfirm title="确定要删除吗 ?" @confirm="onDelete(record)">
                                    <a-button type="text" danger size="small" v-permission="[`yfwy:order-classify:delete`]">删除</a-button>
                                </a-popconfirm>
                            </a-space>
                        </template>
                    </template>
                </a-table>
            </a-card>
        </div>

        <edit :model="editRef" :visible="modalVisible" @cancel="handleEditCancel" @success="reload" />
    </page-container>
</template>

<script lang="ts" setup>
    import { reactive, ref, watch, watchEffect, onMounted } from 'vue';
    import { PlusOutlined, DownOutlined, UpOutlined, DownloadOutlined } from '@ant-design/icons-vue';
    import { getOrderClassifyPage, exportOrderClassifyExcel, deleteOrderClassify } from '@/api/order/cate';
    import type { Pagination, TableFilters, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import Edit from './edit.vue';
    import { downloadByData } from '@/utils/download';
    import { isUndefined } from 'lodash-es';
    import { message } from 'ant-design-vue';
    import { useAppStore } from '@/store/app';
    const appStore = useAppStore();

    const tableRef = ref();
    const exportLoading = ref<boolean>(false);
    const options = [
        {
            label: '户内',
            value: 0,
        },
        {
            label: '公区',
            value: 1,
        },
    ];

    const statusMap = {
        0: { text: '停用', status: 'error' },
        1: { text: '正常', status: 'processing' },
    };

    const typeMap = {
        '0': `报事报修`,
        '1': `投诉`,
    };
    // 查询条件折叠展开
    const expand = ref(false);

    const filteredInfoMap = ref();
    const queryParams = reactive<any>({
        orderType: '0',
    });
    const fetchDataContext = reactive<any>({
        current: 1,
        pageSize: 10,
        tableSize: 'small', // 'default' | 'middle' | 'small'
        stripe: false,
        executeImmediately: true, //是否立即执行查询
        requestParams: { ...queryParams },
    });
    watch(
        filteredInfoMap,
        () => {
            queryParams.status = filteredInfoMap.value?.status;
            fetchDataContext.requestParams = { ...queryParams };
        },
        { immediate: true },
    );
    // 表格列配置
    const mergedColumns = ref<TableColumn[]>([]);
    watchEffect(() => {
        mergedColumns.value = [
            {
                title: '分类名称',
                dataIndex: 'classifyName',
                ellipsis: true,
            },
            {
                title: '归属条线',
                dataIndex: 'orderProfessionalLine',
                ellipsis: true,
                customRender: ({ text }) => (text ? text.replace('品质', '') : ''),
            },
            {
                title: '父级分类',
                dataIndex: 'orderType',
                ellipsis: true,
                customRender: ({ text }) => typeMap[text],
            },
            {
                title: '对应类型',
                dataIndex: 'orderTypeSub',
                ellipsis: true,
                customRender: ({ text }) => formatOptions(text),
            },
            {
                title: '状态',
                dataIndex: 'status',
                ellipsis: true,
            },
            {
                title: '操作',
                dataIndex: 'action',
            },
        ];
    });
    const { state: columnState, dynamicColumns, dynamicColumnItems, handleColumnAllClick, handleColumnChange, reset, move } = useTableDynamicColumns(mergedColumns);

    const [elRef, screenState, { setFull, exitFull }] = useFullscreen();
    // 查询table列表数据
    const { stripe, context: state, reload } = useFetchData(getOrderClassifyPage, fetchDataContext);

    onMounted(() => {});

    const formatOptions = value => {
        if (isUndefined(value)) return '';
        return options
            .filter(item => value.includes(item.value))
            .map(item => item.label)
            .join('、');
    };

    const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
        filteredInfoMap.value = filters;
        fetchDataContext.current = current;
        fetchDataContext.pageSize = pageSize;
    };
    // 查询
    const handleSearch = () => {
        fetchDataContext.current = 1;
        fetchDataContext.requestParams = { ...queryParams };
    };
    // 重置
    const handleReset = () => {
        Object.keys(queryParams).forEach(key => {
            delete queryParams[key];
        });
        queryParams.orderType = '0';
        handleSearch();
    };
    // modal 弹窗
    const modalVisible = ref(false);
    const editRef = reactive<any>({});
    // 新增
    const handleAdd = () => {
        editRef.orderType = queryParams.orderType;
        modalVisible.value = true;
    };
    // 编辑
    const handleEdit = (data: any) => {
        Object.assign(editRef, data);
        modalVisible.value = true;
    };
    // 弹窗关闭
    const handleEditCancel = () => {
        Object.keys(editRef).forEach(key => {
            delete editRef[key];
        });
        modalVisible.value = false;
    };
    // 删除
    const onDelete = (record: any) => {
        deleteOrderClassify(record.id).then(res => {
            message.success('删除成功');
            reload();
        });
    };
    // 导出
    const handleExport = () => {
        exportLoading.value = true;
        exportOrderClassifyExcel({
            ...fetchDataContext.requestParams,
            size: 1000000,
        })
            .then(res => {
                console.log(res);
                downloadByData(res, `${typeMap[queryParams.orderType]}工单分类.xlsx`);
            })
            .finally(() => {
                exportLoading.value = false;
            });
    };
</script>
